package com.own.system.controller;
import com.own.system.utils.Result;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/api/upload")
public class UploadController {
    @PostMapping("/avatar")
    public Result uploadFile(@RequestParam("file") MultipartFile photo) throws IOException {
        //判断是否传入文件
        if (!photo.isEmpty()) {
            //文件上传地址
            String realPath="D:\\daima\\idea\\Permission_System\\system\\src\\main\\resources\\static\\img";
            //用于查看路径是否正确
            //获取文件的名称
            final String fileName = photo.getOriginalFilename();
            //限制文件类型
            String contentType = photo.getContentType();
            String url = "http://localhost:8888/img/"+fileName;
            if ("image/jpeg".equals(contentType) || "image/jpg".equals(contentType) || "image/png".equals(contentType)) {
                File file = new File(realPath, fileName);
                //完成文件上传
                photo.transferTo(file);
                return Result.ok(url).message("上传成功");
            }else {
                return Result.error().message("上传失败");
            }
        }
        return Result.error().message("上传失败");
    }
}
